<script setup lang="ts">
import {addUserLove, findUserById, itemRecommend} from "@/Network/userApi";
import {Ref, ref} from "vue";
import {findSongsByStyle, findSongByTitle, randomGenerateSongsByNum} from "@/Network/songApi";
import type {res} from "@/store/dataType";
import {itemRecSongs, question} from "@/store/songStore";
import {directChineseChat, streamChineseChat} from "@/Network/chatApi";

let userId = ref("11")
let userImg = ref()
findUserById(userId.value).then(res=>{
  // console.log(res.data)
  userImg.value = res.data.userImg
})

randomGenerateSongsByNum(3).then(res=>{
  // console.log(res.data[0].lrc)
})

let style={
  style:"民歌"
}
let styleSongs = ref()
findSongsByStyle(style).then(res=>{
  styleSongs.value = res.data
  // console.log(styleSongs.value)
})



addUserLove(11,1).then(res=>{
  // console.log(res.data)
})

// itemRecommend(11).then(res=>{
//   console.log(res.data)
// })
async function getItemRecSongs(userId){
  let res1:res<any> = await itemRecommend(userId)
  let songs = ref([])
  for(let i=0;i<res1.data.length;i++){
    let songTitle = {
      title:res1.data[i].song
    }
    let res2:res<any> = await findSongByTitle(songTitle)
    songs.value.push(res2.data)
  }
  itemRecSongs.value = songs.value
  console.log(itemRecSongs.value)
}

async function getAnswer1(){
  let q = "你好"
  let res:res<any> = await directChineseChat(q)
  console.log(res.data.choices[0].message.content)
}

async function getAnswer2(){
  let q = "你觉得今天天气怎么样"
  streamChineseChat(q).then(res=>{
    console.log(res.data)
    res.data.on('data',chunk=>{
      console.log(chunk)
    })
    res.data.on('end',()=>{
      console.log("数据已接收完毕")
    })
  })

  // console.log(res.data.choices[0].message.content)
}

let a = ref()
async function getAnswer3(){
  let q = "你觉得今天天气怎么样"
  try{
    // 发送请求
    let response = await fetch("https://api.closeai-proxy.xyz/v1/chat/completions",
        {
          method: "post",
          responseType: "stream",
          headers: {
            Authorization: "Bearer " + 'sk-tHy9pL8JW1QIPM3GMNGCQIitk3rjKtq8j0k2HxGJ6dh9qCvC',
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            "model": "gpt-3.5-turbo",
            "messages": [{"role": "user", "content": "你觉得今天天气怎么样"+" (不能超过50字)"}],
            "stream":true
          }),
        }
    );
    // ok字段判断是否成功获取到数据流
    if (!response.ok) {
      console.log("Network response was not ok");
    }
    // 用来获取一个可读的流的读取器（Reader）以流的方式处理响应体数据
    const reader = response.body.getReader();
    // 将流中的字节数据解码为文本字符串
    const textDecoder = new TextDecoder();
    let result = true;
    let sqlValue = ''
    while (result) {
      // done表示流是否已经完成读取  value包含读取到的数据块
      const { done, value } = await reader.read();
      if (done) {
        result = false;
        break;
      }
      // 拿到的value就是后端分段返回的数据，大多是以data:开头的字符串
      // 需要通过decode方法处理数据块，例如转换为文本或进行其他操作
      textDecoder
          .decode(value)
          .split("\n")
          .forEach((val) => {
            if (!val) return;
            try {
              // 后端返回的流式数据一般都是以data:开头的字符，排除掉data:后就是需要的数据,并将其序列化JSON。parse方便操作键值
              // 具体返回结构可以跟后端约定
              let text = val?.replace("data:", "") || ""
              console.log(text)
              let singleAns = JSON.parse(text)
              // console.log( "输出返回的:"+singleAns.choices[0].delta.content);
              if(singleAns.choices[0].finish_reason !="stop"){//未结束时为null
                sqlValue += singleAns.choices[0].delta.content;
                console.log(sqlValue)
                a.value = sqlValue;
              }
            } catch (err) {}
          });
    }
    console.log(sqlValue,'输出最终返回答案')
  } catch(err) {}
}


// getItemRecSongs(11)
</script>

<template>
  <img :src="userImg" alt="用户图片" class="w-12  rounded-full">
  <button @click="getAnswer1">点击测试chatGPT接口-directChineseChat</button>
  <div></div>
  <button @click="getAnswer3">点击测试chatGPT接口-streamChineseChat</button>
  <div class="flex">
    <div class=" bg-cyan">
      {{a}}
    </div>
  </div>
</template>

<style scoped>

</style>